package org.smart4j.chapter2.util;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by LIJ on 2018/6/13.
 */
public class CastUtil {
    //转为String型
    public static String castString(Object obj){
        return castString(obj,"");
    }

    //转为String型(提供默认值)
    public static String castString(Object obj,String defaultValue){
        return obj != null ? String.valueOf(obj):defaultValue;
    }
    //转为Double型
    public static Double castDouble(Object obj){
        return castDouble(obj,0);
    }

    //转为Double型（提供默认值）
    public static Double castDouble(Object obj,double defaultValue){
        double doubleVlue = defaultValue;
        if(obj != null){
            String strValue = castString(obj);
            if(StringUtils.isNotEmpty(strValue)){
                try {
                    doubleVlue = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    doubleVlue = defaultValue;
                }
            }
        }
        return defaultValue;
    }

    //转为long型
    public static long castLong(Object obj){
        return castLong(obj,0);
    }

    //转为long型（提供默认值）
    public static long castLong(Object obj,long defaultValue){
        long longValue = defaultValue;
        if(obj != null){
            String strValue = castString(obj);
            if(StringUtils.isNotEmpty(strValue)){
                try {
                    longValue = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    //转为int型
    public static int castInt(Object obj){
        return castInt(obj,0);
    }

    //转为int型（提供默认值）
    public  static  int castInt(Object obj,int defaultValue){
        int intValue = defaultValue;
        if(obj != null){
            String strValue = castString(obj);
            if(StringUtils.isNotEmpty(strValue)){
                try {
                    intValue = Integer.parseInt(strValue);
                }
                catch (NumberFormatException e){
                    intValue = defaultValue;
                }
            }
        }
        return  intValue;
    }

    //转为布尔型
    public static boolean castBoolean(Object obj){
        return castBoolean(obj,false);
    }

    //转为布尔型（提供默认值）
    public static boolean castBoolean(Object obj,boolean defaultValue){
        boolean booleanValue = defaultValue;
        if(obj != null){
            booleanValue = Boolean.parseBoolean(castString(obj));
        }
        return booleanValue;
    }
}
